package gameObject.resources3D
{
	import away3d.containers.ObjectContainer3D;
	import away3d.core.math.Quaternion;
	
	import flash.events.Event;
	import flash.geom.Matrix3D;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	public class WeaponResource extends ResourceBase
	{
		////////////////////////////////////////////
		private var _type:int;
		
		private var loader:URLLoader;
		
		private var _wepURL:String;
		private var _wepMeshURL:String;
		////////////////////////////////////////////
		private var _mesh:GameMesh;
		private var _firePoint:ObjectContainer3D = new ObjectContainer3D;
		
		////////////////////////////////////////////
		
		public function get firePoint():ObjectContainer3D
		{
			return _firePoint;
		}

		public function get mesh():GameMesh
		{
			return _mesh;
		}
		
		public function WeaponResource(type:int,id:int,LOD:String)
		{
			super();
			
			_type = type;
			_id = id;
			_LOD = LOD;
		}

		override public function load():void
		{
			if(_id>=0 && !_mesh )
			{
				var preStr:String = "000";
				if (_id>9)preStr = "00";
				if (_id>99)preStr = "0";
				if (_id>999)preStr = "";
					
				var  wepID:String = String(_type)+preStr+String(_id);
				
				_wepURL = Global.assetPath+"models/weapons/wep"+wepID+"_"+_LOD+"_ini.xml";
				
				loader = new URLLoader;
				loader.addEventListener(Event.COMPLETE,wepFileLoaded);
				loader.load(new URLRequest(_wepURL));
			}
		}
		
		////////////////////////////////////////////
		private function wepFileLoaded(e:Event):void
		{
			var ld:URLLoader = e.currentTarget as URLLoader;
			ld.removeEventListener(Event.COMPLETE,wepFileLoaded);
			
			var xml:XML = new XML(ld.data);
			
			var posStr:String = xml.firePoint.@pos;
			var rotStr:String = xml.firePoint.@rot;
			var posAry:Array = posStr.split(",");
			var rotAry:Array = rotStr.split(",");
			
			var rot:Quaternion = new Quaternion(Number(rotAry[0]),Number(rotAry[1]),Number(rotAry[2]),Number(rotAry[3]));
			var tran:Matrix3D = rot.toMatrix3D();
			tran.appendTranslation(Number(posAry[0]),Number(posAry[1]),Number(posAry[2]));
			
			_firePoint.transform = tran;
			
			_wepMeshURL =  Global.assetPath+"models/weapons/"+xml.@mesh;
			_mesh = new GameMesh(_wepMeshURL);
			_mesh.addEventListener(Event.COMPLETE,meshLoaded);
			_mesh.load();
		}
		
		private function meshLoaded(e:Event):void
		{
			_mesh.removeEventListener(Event.COMPLETE,meshLoaded);
			
			addChild(_mesh);
			_mesh.addChild(_firePoint);
			
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
	}
}